﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Base;
using ERP.BusinessEntities;
using System.Data;
using Core;
using Utilities;

namespace MainApp.Modules.Receipt
{
    public class ReceiptEntity: BaseEntity
    {
        public SGVList<ICReceiptItemsInfo> lstICReceiptItems = new SGVList<ICReceiptItemsInfo>();

        public override void InitModuleObjects()
        {
            AddMainObject("ICReceipts", new ICReceiptsInfo());
        }

        public override void InitLists()
        {
            base.InitLists();

            lstICReceiptItems = new SGVList<ICReceiptItemsInfo>();
            lstICReceiptItems.InitList(this, "ICReceipts", "ICReceiptItems", "FK_ICReceipts_ID");

            lstICReceiptItems.Binding("MainScreen", "ICReceiptItemsGridView");
        }

        public override void BeforeSaveList()
        {
            base.BeforeSaveList();

            ICReceiptsInfo Receipt = (ICReceiptsInfo)MainObject;
            if (Receipt == null) return;

            DataSet dsReceiptItems = AppContext.ReceiptItemCtrl.GetAllObjectByColumnValue("FK_ICReceipts_ID", Receipt.ID);
            if (dsReceiptItems != null && dsReceiptItems.Tables.Count > 0)
            {
                foreach (DataRow drReceiptItem in dsReceiptItems.Tables[0].Rows)
                {
                    ICReceiptItemsInfo ReceiptItem = (ICReceiptItemsInfo)AppContext.ReceiptItemCtrl.GetObjectFromDataRow(drReceiptItem);
                    if (ReceiptItem != null)
                        Inventory.UpdateInventory(InventoryDirection.Out, InventoryType.OnHand, ReceiptItem.FK_ICProducts_ID, ReceiptItem.FK_ICStocks_ID,
                            ReceiptItem.BatchNo, ReceiptItem.LotNo, ReceiptItem.SerialNo, ReceiptItem.Qty);

                }
            }

        }

        public override void  AfterSaveList()
        {
            base.AfterSaveList();

            ICReceiptsInfo Receipt = (ICReceiptsInfo)MainObject;
            if (Receipt == null) return;

            DataSet dsReceiptItems = AppContext.ReceiptItemCtrl.GetAllObjectByColumnValue("FK_ICReceipts_ID", Receipt.ID);
            if (dsReceiptItems != null && dsReceiptItems.Tables.Count > 0)
            {
                foreach (DataRow drReceiptItem in dsReceiptItems.Tables[0].Rows)
                {
                    ICReceiptItemsInfo ReceiptItem = (ICReceiptItemsInfo)AppContext.ReceiptItemCtrl.GetObjectFromDataRow(drReceiptItem);
                    if (ReceiptItem != null)
                        Inventory.UpdateInventory(InventoryDirection.In, InventoryType.OnHand, ReceiptItem.FK_ICProducts_ID, ReceiptItem.FK_ICStocks_ID,
                            ReceiptItem.BatchNo, ReceiptItem.LotNo, ReceiptItem.SerialNo, ReceiptItem.Qty);

                }
            }

        }
    }
}
